package edu.hcmus.sow.web.security;

import javax.servlet.http.HttpServletRequest;

import org.springframework.security.core.SpringSecurityCoreVersion;
import org.springframework.security.web.authentication.WebAuthenticationDetails;

public class CustomWebAuthenticationDetails extends WebAuthenticationDetails {

   private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;

   // ~ Instance fields
   // ================================================================================================

   private final String subDomain;

   // ~ Constructors
   // ===================================================================================================

   /**
    * Records the remote address and will also set the session Id if a session already exists (it
    * won't create one).
    * 
    * @param request
    *           that the authentication request was received from
    */
   public CustomWebAuthenticationDetails(HttpServletRequest request) {
      super(request);

      // test
      String domain = request.getServerName();
      String[] parts = domain.split("\\.");
      String subdomain = parts.length < 3 ? null : parts[0];
      subdomain = "www".equals(subdomain) ? null : subdomain;
      // end test

      // this.subDomain = request.getParameter("subdomain");
      this.subDomain = subdomain;
   }

   // ~ Methods
   // ========================================================================================================

   public boolean equals(Object obj) {
      super.equals(obj);

      if (obj instanceof CustomWebAuthenticationDetails) {
         CustomWebAuthenticationDetails rhs = (CustomWebAuthenticationDetails) obj;

         if ((subDomain == null) && (rhs.getSubDomain() != null)) {
            return false;
         }

         if ((subDomain != null) && (rhs.getSubDomain() == null)) {
            return false;
         }

         if (subDomain != null) {
            if (!subDomain.equals(rhs.getSubDomain())) {
               return false;
            }
         }

         return true;
      }

      return false;
   }

   /**
    * Indicates the Sub Domain the authentication request was received from.
    * 
    * @return the subDomain
    */
   public String getSubDomain() {
      return subDomain;
   }

   public int hashCode() {
      int code = super.hashCode();

      if (this.subDomain != null) {
         code = code * (this.subDomain.hashCode() % 7);
      }

      return code;
   }

   public String toString() {
      StringBuilder sb = new StringBuilder();
      sb.append(super.toString()).append("; ");
      sb.append("SubDomain: ").append(this.getSubDomain());

      return sb.toString();
   }

}
